package com.zhenyi.tuangou.interceptor;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.utils.AuthUtils;

import cn.hutool.core.text.StrFormatter;
import cn.hutool.core.util.URLUtil;

public class AuthInterceptor implements Interceptor {

	protected final String HOST = PropKit.get("host");
	protected final String APP_ID = PropKit.get("appId");

	@Override
	public void intercept(Invocation inv) {
		Controller controller = inv.getController();
		if (AuthUtils.verify(controller)) {
			inv.invoke();
		} else {
			System.out.println("APP_ID: " + APP_ID);
			String rd = HOST + "/tg/auth";
			System.out.println(rd);
			rd = URLUtil.encode(rd);
			String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={}&redirect_uri={}&response_type=code&scope=snsapi_userinfo&state={}#wechat_redirect";
			String request = getRequestUrl(inv);
			url = StrFormatter.format(url, APP_ID, rd, URLUtil.encode(request));
			System.out.println(url);
			controller.redirect(url);
			return;
		}
	}

	private String getRequestUrl(Invocation inv) {
		String url = inv.getController().getRequest().getRequestURL().toString();
		String queryurl = inv.getController().getRequest().getQueryString();
		if (StrKit.notBlank(queryurl)) {
			url = url + "?" + queryurl;
		}
		return url;
	}
}
